const app = getApp();

Page({
  data: {
    username: '',
    password: '',
    loading: false
  },

  onLoad() {
    console.log('📱 Login page loaded');
    // 检查是否已经登录
    if (app.globalData.userInfo) {
      console.log('ℹ️ User already logged in, redirecting...');
      wx.switchTab({ url: '/pages/index/index' });
    }
  },

  onUsernameInput(e) {
    this.setData({ username: e.detail.value });
  },

  onPasswordInput(e) {
    this.setData({ password: e.detail.value });
  },

  async onLogin() {
    const { username, password } = this.data;
    
    if (!username || !password) {
      wx.showToast({ title: '请填写完整', icon: 'none' });
      return;
    }

    this.setData({ loading: true });
    console.log('🔐 Attempting login...');

    try {
      const result = await app.request('/users/login', 'POST', {
        username: username,
        password: password
      });

      console.log('🎉 Login success:', result);
      
      if (!result.token) {
        throw new Error('服务器返回的token为空');
      }

      if (!result.user) {
        throw new Error('服务器返回的用户信息为空');
      }

      // 使用新的保存方法
      app.saveUserInfo(result.token, result.user);

      wx.showToast({ 
        title: '登录成功', 
        icon: 'success',
        success: () => {
          setTimeout(() => {
            console.log('🔄 Navigating to index...');
            // 返回上一页或跳转到首页
            const pages = getCurrentPages();
            if (pages.length > 1) {
              wx.navigateBack();
            } else {
              wx.switchTab({ url: '/pages/index/index' });
            }
          }, 1500);
        }
      });
    } catch (error) {
      console.error('❌ Login error:', error);
      wx.showToast({ 
        title: error.error || '登录失败', 
        icon: 'none',
        duration: 3000
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  onRegister() {
    wx.navigateTo({ url: '/pages/user/register/register' });
  }
});